// Copyright (C) 2020-2022 Intel Corporation
//
// SPDX-License-Identifier: MIT

import React, { ReactNode, useRef, useState } from 'react';
import { Button, Drawer, Modal, Progress, Tooltip } from 'antd/lib';
import { ActionType, ProColumns, ProFormInstance, ProTable } from '@ant-design/pro-components';
import { ConfigProvider, DatePicker, message } from 'antd';
import moment, { Moment } from 'moment';
import TaskDetailComponent from '../task-detail/task-detail';
import { TaskBatchType } from '../../typings/task.d';
import { closeBatchTask, fetchCreateUserList, fetchRelationUsersByFiler, fetchTaskList, fetchTaskStatusTypes } from 'apis/task';
import AuthPerm from 'components/common/AuthPerm';

enum TaskStateTypeEnum {
    Started = 1, // 进行中
    Finished = 2, // 已完结
    Closed = 3, // 已关闭
}

const taskStateTypeMapping = {
    1: '进行中',
    2: '已完结',
    3: '已关闭',
};

const stateColorMapping = {
    1: '#165DFF',
    2: '#00B42A',
    3: '#000',
};

type RangeValue = [Moment | null, Moment | null] | null;

function TaskManagerPageComponent(): JSX.Element {
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [pageInfo, setPageInfo] = useState({ pageIndex: 1, pageSize: 20, total: 0 });
    const { RangePicker } = DatePicker;
    const [showDrawer, setShowDrawer] = useState(false); // 显示隐藏创建任务modal
    const [currentTask, setCurrentTask] = useState<TaskBatchType>(); // 当前子任务

    async function closeTaskBatch(record: TaskBatchType): Promise<void> {
        if (record.batchTaskStatus === TaskStateTypeEnum.Started && record.completeProgress === 0) {
            await closeBatchTask({ batchTaskId: record.id });
            message.success(`任务批次${record.batchTaskName}关闭成功！`)
        }
    }

    // 1--代表标注员，2--代表初审员 3--代表复审员
    const fetchOptions = async (type: number) => {
        const res = await fetchRelationUsersByFiler({ type });
        return res.userList.map(v => {
            return { label: v.userName, value: v.userId };
        });
    }

    const getCreateUserList = async () => {
        const res = await fetchCreateUserList({});
        return res.userList.map(v => {
            return { label: v.userName, value: v.userId };
        })
    }

    const getTaskStateOption = async () => {
        const res = await fetchTaskStatusTypes({});
        return res.statusList.map(v => {
            return { label: v.statusName, value: v.status };
        });
    }
    const columns: ProColumns<TaskBatchType>[] = [
        {
            title: '任务批次ID',
            dataIndex: 'id',
            sorter: true,
            key: 'id',
            valueType: 'text',
            search: true,
            order: 2,
            width: 200,
            fieldProps: {
                placeholder: '请输入任务批次ID',
            },
            colSize: 0.9,
        },
        {
            title: '任务批次名称',
            dataIndex: 'batchTaskName',
            sorter: false,
            key: 'batchTaskName',
            valueType: 'text',
            search: true,
            order: 3,
            fieldProps: {
                placeholder: '请输入任务批次名称',
            },
            colSize: 0.9,
        },
        {
            title: '图片数量',
            dataIndex: 'picAmount',
            sorter: true,
            search: false,
            valueType: 'text',
            key: 'imgCount',
        },
        {
            title: '子任务数量',
            dataIndex: 'subTaskAmount',
            sorter: true,
            search: false,
            valueType: 'text',
            key: 'subTaskAmount',
        },
        {
            title: '完成进度',
            dataIndex: 'completeProgress',
            sorter: true,
            search: false,
            valueType: 'text',
            key: 'completeProgress',
            width: 180,
            render: (text, record) => [
                <Tooltip
                    title={`复审通过子任务数${record.subTaskRecheckAmount}/子任务总数${record.subTaskAmount}（不包含已关闭的子任务）=${record.completeProgress}%`}
                >
                    <span className='flex flex-items-center gap-5px'>
                        <Progress className='w-120px' percent={record.completeProgress} showInfo={false} size="small" strokeColor={stateColorMapping[record.batchTaskStatus]} />
                        <span className='block w-38px text-align-left'>
                            {record.completeProgress}%
                        </span>
                    </span>

                </Tooltip>,
            ],
        },
        {
            title: '批注状态',
            dataIndex: 'batchTaskStatusName',
            key: 'batchTaskStatusName',
            sorter: false,
            order: 8,
            search: true,
            valueType: 'select',
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择批注状态',
            },
            request: async () => {
                return getTaskStateOption();
            },
            render: (text: ReactNode, record, index: number, action) => [
                (<span
                    className='flex flex-items-center'
                    style={{ color: stateColorMapping[record.batchTaskStatus] }}
                >
                    <i style={{
                        display: 'inline-block',
                        marginRight: '6px',
                        width: '4px',
                        height: '4px',
                        borderRadius: '2px',
                        backgroundColor: stateColorMapping[record.batchTaskStatus],
                    }}
                    />
                    {text}
                </span>),
            ],
        },
        {
            title: '创建人',
            dataIndex: 'createUserName',
            key: 'createUserName',
            sorter: false,
            search: true,
            order: 1,
            valueType: 'select',
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择创建人',
            },
            request: async () => {
                return getCreateUserList();
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            sorter: true,
            valueType: 'dateTime',
            search: true,
            order: 7,
            colSize: 1.3,
            width: 180,
            renderFormItem: (item, { type, defaultRender, ...rest }, form) => (
                <RangePicker
                    showTime={false}
                    placeholder={['开始日期', '结束日期']}
                    format='YYYY-MM-DD HH:mm:ss'
                />
            ),
        },
        {
            title: '标注员',
            dataIndex: 'labeler',
            key: 'labeler',
            sorter: false,
            search: true,
            order: 6,
            colSize: 1.2,
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择标注员',
            },
            request: async () => {
                return fetchOptions(1)
            },
        },
        {
            title: '初审员',
            dataIndex: 'firstChecker',
            key: 'firstChecker',
            sorter: false,
            search: true,
            order: 5,
            colSize: 1.2,
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择初审员',
            },
            request: async () => {
                return fetchOptions(2)
            },
        },
        {
            title: '复审员',
            dataIndex: 'rechecker',
            key: 'rechecker',
            sorter: true,
            search: true,
            order: 4,
            fieldProps: {
                mode: 'multiple',
                placeholder: '请选择复审员',
            },
            request: async () => {
                return fetchOptions(3)
            },
        },
        {
            title: '操作',
            dataIndex: 'handler',
            sorter: false,
            key: 'handler',
            valueType: 'option',
            search: false,
            fixed: 'right',
            render: (text, record) => [
                <ConfigProvider
                    theme={{
                        components: {
                            Button: {
                                paddingInline: 0,
                            }

                        }
                    }}
                >
                    {record.batchTaskStatus === TaskStateTypeEnum.Started && record.completeProgress === 0 ?
                        <AuthPerm permission='closeTaskBatch'>
                            <Button
                                type='link'
                                size='middle'
                                onClick={() => {
                                    const modal = Modal.info({});
                                    modal.update({
                                        title: '关闭任务批次确认',
                                        content: '关闭任务批次后所有子任务将同步关闭，且不能恢复，请确认是否关闭',
                                        closable: false,
                                        okText: '确定关闭',
                                        onOk: () => {
                                            closeTaskBatch(record);
                                            modal.destroy();
                                        },
                                        onCancel: () => {
                                            modal.destroy();
                                        },
                                        cancelText: '取消',
                                    });
                                }}
                            >
                                关闭
                            </Button>
                        </AuthPerm>
                        : ''}
                    <Button
                        type='link'
                        size='middle'
                        onClick={() => {
                            setCurrentTask(record);
                            setShowDrawer(true);
                        }}
                    >
                        查看
                    </Button>

                </ConfigProvider>

            ],
        },
    ];

    const pageSizeOptions = [10, 20, 50, 100];

    function search(): void {
        formRef.current.submit();
        tableRef.current.reload();
    }
    function clear(): void {
        formRef.current?.resetFields();
        search();
    }

    return (
        <>
            <ProTable<TaskBatchType>
                actionRef={tableRef}
                formRef={formRef}
                columns={columns}
                request={async (params, sort, filter) => {
                    const { id, batchTaskStatusName = [], batchTaskName, createTime = [], labeler = [], firstChecker = [], rechecker = [], createName = [] } = params;
                    const [createTimeStart, createTimeEnd] = createTime;
                    try {
                        let sortKey;
                        let sortType;
                        Object.keys(sort).forEach(v => {
                            sortKey = v;
                            sortType = sort[v];
                        })
                        const sortAscColumn = sortType === 'ascend' ? sortKey : ''; //升序字段
                        const sortDescColumn = sortType === 'descend' ? sortKey : '';
                        const r = await fetchTaskList({
                            pageIndex: params.current,
                            pageSize: params.pageSize,
                            id,
                            labelers: labeler,
                            firstCheckers: firstChecker,
                            recheckers: rechecker,
                            batchTaskName,
                            batchTaskStatus: batchTaskStatusName,
                            createTimeStart,
                            createTimeEnd,
                            createUserIds: createName,
                            sortAscColumn,
                            sortDescColumn
                        });
                        const arr = r ? (r?.dataList).map(v => {
                            return {
                                key: v.id,
                                ...v
                            };
                        }) : [];
                        return {
                            data: arr,
                            success: true,
                            total: r ? r.totalRow : 0,
                        };
                    } catch (error) {
                        return {
                            data: [],
                            success: true,
                            total: 0,
                        };
                    }
                }}
                scroll={{ y: 'calc(100vh - 330px)' }}
                pagination={{
                    pageSize: pageInfo.pageSize,
                    current: pageInfo.pageIndex,
                    total: pageInfo.total,
                    pageSizeOptions,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total}条`,
                    onChange: (page, pageSize) => {
                        setPageInfo({
                            ...pageInfo,
                            pageIndex: page,
                        });
                    },
                }}
                search={{
                    defaultCollapsed: false,
                    collapseRender: false,
                    searchText: '查询',
                    labelWidth: 'auto',
                    span: 5,
                    className: 'search-wrapper',
                    optionRender: () => [
                        <Button key='clear' onClick={() => clear()}>重置</Button>,
                        <Button key='search' type='primary' onClick={() => search()}>查询</Button>,
                    ],
                }}
                tableAlertRender={false}
                options={{
                    density: false,
                    setting: false,
                    reload: false,
                }}
            />
            <Drawer
                title={(
                    <div className='flex flex-justify-between flex-items-center'>
                        <div>任务详情</div>
                        <div className='flex flex-items-center flex-justify-end font-normal gap-6px text-14px'>
                            <span
                                className='flex flex-items-center gap-6px'
                                style={{
                                    color: stateColorMapping[currentTask?.batchTaskStatus || 0],
                                    wordBreak: 'keep-all',
                                }}
                            >
                                <i style={{
                                    display: 'inline-block',
                                    width: '5px',
                                    height: '5px',
                                    borderRadius: '2.5px',
                                    backgroundColor: stateColorMapping[currentTask?.batchTaskStatus || 0],
                                }}
                                />
                                <span>{taskStateTypeMapping[currentTask?.batchTaskStatus || 0]}</span>
                            </span>
                            &nbsp;&nbsp;
                            <Tooltip title={`复审通过子任务数${currentTask?.subTaskRecheckAmount}/子任务总数${currentTask?.subTaskAmount}（不包含已关闭的子任务）=${currentTask?.completeProgress}%`}>
                                <Progress className='w-120px' percent={currentTask?.completeProgress} showInfo={false} />
                                <span className='m-l-6px'>{currentTask?.completeProgress} %</span>
                            </Tooltip>
                        </div>
                    </div>
                )}
                placement='right'
                width='max(43%, 840px)'
                onClose={() => {
                    setShowDrawer(false);
                }}
                destroyOnClose={true}
                open={showDrawer}
                bodyStyle={{
                    padding: '0',
                }}
            >
                <TaskDetailComponent task={currentTask} />
            </Drawer>
        </>
    );
}

export default React.memo(TaskManagerPageComponent);
